package com.ego.admin.config;

import com.ego.admin.oauth.OauthFilter;
import com.ego.admin.oauth.ShiroRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @program: ego
 * @description: Shiro配置
 * @author: KamTang
 * @create: 2022-11-13 09:44
 **/
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean (@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 添加Shiro的内置过滤器

        /*
        anon：无需认证就可以访问
        authc：必须认证才能访问
        user：必须拥有 记住我 给你才能使用
        perms：拥有对某个资源的权限才能访问
        role：拥有某个角色权限才能访问
         */
        // 拦截
        // oauth过滤
        Map<String, Filter> filters = new HashMap<>(1);
        filters.put("oauth2", new OauthFilter());
        shiroFilterFactoryBean.setFilters(filters);

        Map<String, String> filterMap = new LinkedHashMap<>();
        filterMap.put("/druid/**", "anon");
        filterMap.put("/sys/captcha.jpg", "anon");
        filterMap.put("/sys/login", "anon");
        filterMap.put("/**", "oauth2");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        return shiroFilterFactoryBean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager (@Qualifier("shiroRealm") ShiroRealm shiroRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(shiroRealm);
        return defaultWebSecurityManager;
    }

    @Bean(name = "shiroRealm")
    public ShiroRealm shiroRealm () {
        return new ShiroRealm();
    }
}

